package peer.view;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Scanner;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import model.dto.FileDTO;
import model.dto.NetPackage;
import model.dto.UserDTO;
import model.enums.RequestType;
import peer.model.connections.NetPackagesManager;
import peer.model.connections.NetUtil;
import peer.model.consts.ConnectionsConsts;
import peer.model.transfer.TransfersManager;

public class Ventana extends JFrame {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private void updateDownloadList(){
		
	}
	
	private void updateUploadList(){
		
	}

	private class DownloadFileAction implements ActionListener{

		@SuppressWarnings("unchecked")
		@Override
		public void actionPerformed(ActionEvent e) {
			Socket sck=null;
			try {
				sck = new Socket(ConnectionsConsts.MAIN_SERVER_IP, ConnectionsConsts.MAIN_SERVER_PORT);
				NetPackage netRequest=new NetPackage(RequestType.USERS_FOR_FILE, null, null);
				Integer fileID=Integer.valueOf(Ventana.this.jtblResultados.getValueAt(Ventana.this.jtblResultados.getSelectedRow(), Ventana.this.jtblResultados.getColumn("id").getModelIndex()).toString());
				FileDTO fileData=new FileDTO(fileID);
				fileData.setFilename(Ventana.this.jtblResultados.getValueAt(Ventana.this.jtblResultados.getSelectedRow(), Ventana.this.jtblResultados.getColumn("filename").getModelIndex()).toString());
				fileData.setExtension(Ventana.this.jtblResultados.getValueAt(Ventana.this.jtblResultados.getSelectedRow(), Ventana.this.jtblResultados.getColumn("extension").getModelIndex()).toString());
				fileData.setSize(Long.parseLong(Ventana.this.jtblResultados.getValueAt(Ventana.this.jtblResultados.getSelectedRow(), Ventana.this.jtblResultados.getColumn("size").getModelIndex()).toString()));
				netRequest.setContent(fileData);

				NetPackage response=NetPackagesManager.sendPackage(new HashMap<String, Class>(), new Scanner(sck.getInputStream()), sck.getOutputStream(), netRequest);
				//System.out.println(new XStream(new DomDriver()).toXML(response));

				TransfersManager.createNewFileDownloadInstance((ArrayList<UserDTO>) response.getContent(), (FileDTO) response.getHeader());

			} catch (UnknownHostException e1) {
				e1.printStackTrace(System.err);
				JOptionPane.showMessageDialog(Ventana.this, e1.getMessage());
			} catch (IOException e1) {
				e1.printStackTrace(System.err);
				JOptionPane.showMessageDialog(Ventana.this, e1.getMessage());
			} catch (IllegalArgumentException e1) {
				e1.printStackTrace(System.err);
				JOptionPane.showMessageDialog(Ventana.this, e1.getMessage());
			}finally{
				try {
					sck.close();
				} catch (IOException e1) {
					e1.printStackTrace(System.err);
					JOptionPane.showMessageDialog(Ventana.this, e1.getMessage());
				}
			}
		}

	}

	private class SearchFileAction implements ActionListener{

		@SuppressWarnings("unchecked")
		@Override
		public void actionPerformed(ActionEvent e) {

			Socket sck=null;
			try {
				sck = new Socket(ConnectionsConsts.MAIN_SERVER_IP, ConnectionsConsts.MAIN_SERVER_PORT);
				NetPackage netRequest=new NetPackage(RequestType.FILTERED_FILES, null, null);

				int idValue=0;
				if(!jtxtFileID.getText().equals("")){
					idValue=Integer.valueOf(jtxtFileID.getText());
				}
				netRequest.setContent(new FileDTO(idValue, 0, jtxtFileName.getText(), jtxtFileExtension.getText(), 0L));
				NetPackage response=NetPackagesManager.sendPackage(new HashMap<String, Class>(), new Scanner(sck.getInputStream()), sck.getOutputStream(), netRequest);
				DefaultTableModel newModel=TableUtil.parseGenericResponse((ArrayList<Object>) response.getContent());
				if(newModel.getRowCount()>0){
					Ventana.this.jbtnDownload.setEnabled(true);
				}else{
					Ventana.this.jbtnDownload.setEnabled(false);
				}
				Ventana.this.jtblResultados.setModel(newModel);
				Ventana.this.jtblResultados.repaint();
			} catch (UnknownHostException e1) {
				e1.printStackTrace(System.err);
				JOptionPane.showMessageDialog(Ventana.this, e1.getMessage());
			} catch (IOException e1) {
				e1.printStackTrace(System.err);
				JOptionPane.showMessageDialog(Ventana.this, e1.getMessage());
			} catch (IllegalArgumentException e1) {
				e1.printStackTrace(System.err);
				JOptionPane.showMessageDialog(Ventana.this, e1.getMessage());
			}finally{
				try {
					sck.close();
				} catch (IOException e1) {
					e1.printStackTrace(System.err);
					JOptionPane.showMessageDialog(Ventana.this, e1.getMessage());
				}
			}
		}

	}

	private static final Integer DEFAULT_HEIGHT = 500;
	private static final Integer DEFAULT_WIDTH = 500;

	private JTabbedPane jtabMenu;


	//-----------------------------Searching
	private JPanel jpnlFileSearch;
	private JPanel jpnlControles;
	private JPanel jpnlResultados;

	private JTable jtblResultados;
	private JTextField jtxtFileName;
	private JTextField jtxtFileExtension;
	private JTextField jtxtFileID;

	private JButton jbtnDownload;

	//------------------------------Transfers

	private JPanel jpnlTransfer;
	private JTable jtblUpload;
	private JTable jtblDownload;

	private JButton createButton(String name, ActionListener listener){
		JButton btn=new JButton(name);
		btn.addActionListener(listener);
		return btn;
	}

	public Ventana(){
		super();
		this.setTitle("[Peer] Local IP Address: " + NetUtil.getPrimaryPrivateIP().getHostAddress());
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setBounds(10, 10, DEFAULT_WIDTH, DEFAULT_HEIGHT);
		this.setLayout(null);
		this.setResizable(false);
		this.jtabMenu=new JTabbedPane();
		this.jtabMenu.setBounds(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT);

		this.createFileSearchComponents();
		this.createDownloadTabComponents();

		this.jtabMenu.addTab("File Search", jpnlFileSearch);
		this.jtabMenu.addTab("Active Transfers", jpnlTransfer);
		this.getContentPane().add(this.jtabMenu);
	}

	private void createFileSearchComponents(){
		this.jpnlFileSearch=new JPanel();
			this.jpnlFileSearch.setBounds(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT);
			this.jpnlFileSearch.setLayout(new BorderLayout());

		this.jpnlControles=new JPanel();
			this.jpnlControles.setLayout(new GridLayout(0, 2));

			this.jpnlControles.add(new JLabel("FileName:"));
			this.jtxtFileName=new JTextField();
			this.jpnlControles.add(jtxtFileName);

			this.jpnlControles.add(new JLabel("FileExtension:"));
			this.jtxtFileExtension=new JTextField();
			this.jpnlControles.add(jtxtFileExtension);

			this.jpnlControles.add(new JLabel("FileID:"));
			this.jtxtFileID=new JTextField();
			this.jpnlControles.add(jtxtFileID);

			this.jpnlControles.add(this.createButton("Buscar", new SearchFileAction()));
			this.jbtnDownload=this.createButton("Descargar Seleccionado", new DownloadFileAction());
			this.jbtnDownload.setEnabled(false);
			this.jpnlControles.add(this.jbtnDownload);
		this.jpnlResultados=new JPanel();
			this.jpnlResultados.setLayout(new FlowLayout());
			jtblResultados = new JTable();
			JScrollPane jscr_results = new JScrollPane(jtblResultados);
			this.jpnlResultados.add(jscr_results);

		this.jpnlFileSearch.add(this.jpnlResultados, BorderLayout.CENTER);
		this.jpnlFileSearch.add(this.jpnlControles, BorderLayout.NORTH);
	}

	private void createDownloadTabComponents(){
		this.jpnlTransfer=new JPanel();
		this.jpnlTransfer.setBounds(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT);
		this.jpnlTransfer.setLayout(new GridLayout(2, 0));

		jtblDownload=new JTable();
		JScrollPane jscrDownload = new JScrollPane(jtblDownload);
		this.jpnlTransfer.add(jscrDownload);

		jtblUpload=new JTable();
		JScrollPane jscrUpload = new JScrollPane(jtblUpload);
		this.jpnlTransfer.add(jscrUpload);

	}

}
